package com.chen.cloudpicture.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chen.cloudpicture.api.aliyunai.AliYunAiApi;
import com.chen.cloudpicture.api.aliyunai.model.CreateOutPaintingTaskRequest;
import com.chen.cloudpicture.api.aliyunai.model.CreateOutPaintingTaskResponse;
import com.chen.cloudpicture.exception.BusinessException;
import com.chen.cloudpicture.exception.ErrorCode;
import com.chen.cloudpicture.exception.ThrowUtils;
import com.chen.cloudpicture.manager.CosManager;
import com.chen.cloudpicture.manager.upload.FilePictureUpload;
import com.chen.cloudpicture.manager.upload.PictureUploadTemplate;
import com.chen.cloudpicture.manager.upload.UrlPictureUpload;
import com.chen.cloudpicture.model.dto.file.UploadPictureResult;
import com.chen.cloudpicture.model.dto.picture.*;
import com.chen.cloudpicture.model.entity.Picture;
import com.chen.cloudpicture.model.entity.Space;
import com.chen.cloudpicture.model.entity.User;
import com.chen.cloudpicture.model.enums.PictureReviewStatusEnum;
import com.chen.cloudpicture.model.vo.PictureVO;
import com.chen.cloudpicture.model.vo.UserVO;
import com.chen.cloudpicture.service.PictureService;
import com.chen.cloudpicture.mapper.PictureMapper;
import com.chen.cloudpicture.service.SpaceService;
import com.chen.cloudpicture.service.UserService;
import com.chen.cloudpicture.utils.ColorSimilarUtils;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.BeanUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.io.IOException;
import java.util.*;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 * @author 25480
 * @description 针对表【picture(图片)】的数据库操作Service实现
 * @createDate 2025-07-26 15:08:27
 */
@Service
@Slf4j
public class PictureServiceImpl extends ServiceImpl<PictureMapper, Picture>
        implements PictureService {

    //    @Resource
//    private FileManager fileManager;
    @Resource
    private UserService userService;
    @Resource
    private FilePictureUpload filePictureUpload;
    @Resource
    private UrlPictureUpload urlPictureUpload;
    @Resource
    private SpaceService spaceService;
    @Resource
    private CosManager cosManager;
    @Resource
    private TransactionTemplate transactionTemplate;
    @Resource
    private ThreadPoolExecutor customExecutor;
    @Resource
    private AliYunAiApi aliYunAiApi;

    /**
     * 本地文件方式图片上传
     *
     * @param inputSource 文件输入源，可以是MultipartFile或其他类型
     */
    @Override
    public PictureVO uploadPicture(Object inputSource, PictureUploadRequest pictureUploadRequest, User loginUser) {
        // 校验参数
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NO_AUTH_ERROR);
        Long spaceId = pictureUploadRequest.getSpaceId(); // 校验空间
        if (spaceId != null) {
            Space space = spaceService.getById(spaceId);
            ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
            // 改为使用统一权限校验框架
//            if (!loginUser.getId().equals(space.getUserId())) // Long等包装类型必须用equals()，它比较的是值，==比较的是引用地址是否相同
//                throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "没有空间权限");
            // 校验额度
            if (space.getTotalCount() >= space.getMaxCount()) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "空间条数不足");
            }
            if (space.getTotalSize() >= space.getMaxSize()) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "空间大小不足");
            }
        }
        // // 用于判断是新增还是更新图片
        Long pictureId = null;
        if (pictureUploadRequest != null) {
            pictureId = pictureUploadRequest.getId();
        }
        // 如果图片已经有id就说明是更新，判断图片是否存在
        if (pictureId != null) {
            Picture oldPicture = getById(pictureId);
            ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR, "图片不存在");
            // 改为使用统一权限校验框架
//            // 仅本人或管理员可编辑图片
//            if (!oldPicture.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
//                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
//            }
//            // 为了严谨，再校验一下空间
//            else if(ObjUtil.notEqual(spaceId, oldPicture.getSpaceId()))
//                throw new BusinessException(ErrorCode.PARAMS_ERROR, "空间 id 不一致");
        }
        // 上传图片（公共），得到图片信息,按照用户id划分目录 ==> 按照空间划分目录
        String updatePathPrefix;
        if(spaceId == null)
            updatePathPrefix = String.format("public/%s", loginUser.getId());
        else
            updatePathPrefix = String.format("space/%s", spaceId);
        // 一个方法实现两种上传方式，整个流程只有这里实现有区别，只用了几行代码就实现了两种方式的兼容
        //根据 inputSource 的类型区分上传方式
        PictureUploadTemplate pictureUploadTemplate = filePictureUpload;
        if (inputSource instanceof String)
            pictureUploadTemplate = urlPictureUpload;
        UploadPictureResult uploadPictureResult = pictureUploadTemplate.uploadPicture(inputSource, updatePathPrefix);

        // 构造要入库的图片信息
        Picture picture = new Picture();
        picture.setUrl(uploadPictureResult.getUrl());
        picture.setSpaceId(spaceId);
        picture.setThumbnailUrl(uploadPictureResult.getThumbnailUrl());
        String picName = uploadPictureResult.getPicName();
        if(pictureUploadRequest != null && StrUtil.isNotBlank(pictureUploadRequest.getPicName())) {
            // 如果有传入图片名称，就使用传入的名称
            picName = pictureUploadRequest.getPicName();
        }
        picture.setName(picName);
        picture.setPicSize(uploadPictureResult.getPicSize());
        picture.setPicWidth(uploadPictureResult.getPicWidth());
        picture.setPicHeight(uploadPictureResult.getPicHeight());
        picture.setPicScale(uploadPictureResult.getPicScale());
        picture.setPicFormat(uploadPictureResult.getPicFormat());
        picture.setUserId(loginUser.getId());
        picture.setPicColor(uploadPictureResult.getPicColor());
        // 补充审核参数
        fillReviewParams(picture, loginUser);
        // 操作数据库
        // 如果 pictureId 不为空，表示更新，否则是新增
        if (pictureId != null) {
            // 如果是更新，需要补充 id 和编辑时间
            picture.setId(pictureId);
            picture.setEditTime(new Date());
        }
        // 开启事务(同一个方法内调用同类多个方法，可用编程式事务避免事务失效)
        transactionTemplate.execute(status -> {
            // 插入数据
            boolean saveResult = saveOrUpdate(picture);
            ThrowUtils.throwIf(!saveResult, ErrorCode.OPERATION_ERROR, "上传图片失败");
            // 更新额度
            if(spaceId != null){
                boolean update = spaceService.lambdaUpdate()
                        .eq(Space::getId, spaceId)
                        .setSql("totalSize = totalSize + " + picture.getPicSize())
                        .setSql("totalCount = totalCount + 1")
                        .update();
                ThrowUtils.throwIf(!update, ErrorCode.OPERATION_ERROR, "额度更新失败");
            }
            return picture; // 返回值没用到但必须有一个返回，可以随便传一个返回值
        });
        return PictureVO.objToVo(picture);
    }

    /**
     * 快速构建图片查询条件
     */
    @Override
    public QueryWrapper<Picture> getQueryWrapper(PictureQueryRequest pictureQueryRequest) {
        QueryWrapper<Picture> queryWrapper = new QueryWrapper<>();
        if (pictureQueryRequest == null) {
            return queryWrapper;
        }
        // 从对象中取值
        Long id = pictureQueryRequest.getId();
        String name = pictureQueryRequest.getName();
        String introduction = pictureQueryRequest.getIntroduction();
        String category = pictureQueryRequest.getCategory();
        List<String> tags = pictureQueryRequest.getTags();
        Long picSize = pictureQueryRequest.getPicSize();
        Integer picWidth = pictureQueryRequest.getPicWidth();
        Integer picHeight = pictureQueryRequest.getPicHeight();
        Double picScale = pictureQueryRequest.getPicScale();
        String picFormat = pictureQueryRequest.getPicFormat();
        String searchText = pictureQueryRequest.getSearchText();
        Long userId = pictureQueryRequest.getUserId();
        Long spaceId = pictureQueryRequest.getSpaceId();
        boolean nullSpaceId = pictureQueryRequest.isNullSpaceId();
        Date startEditTime = pictureQueryRequest.getStartEditTime();
        Date endEditTime = pictureQueryRequest.getEndEditTime();
        String sortField = pictureQueryRequest.getSortField();
        String sortOrder = pictureQueryRequest.getSortOrder();
        Integer reviewStatus = pictureQueryRequest.getReviewStatus();
        String reviewMessage = pictureQueryRequest.getReviewMessage();
        Long reviewerId = pictureQueryRequest.getReviewerId();

        // 从多字段中搜索(searchText可能包含name或introduction)
        if (StrUtil.isNotBlank(searchText)) {
            // 需要拼接查询条件，使用lambda表达式，%是SQL中的通配符，代表零个或多个字符
            // and(name like '%searchText%' or introduction like '%searchText%')
            queryWrapper.and(
                    qw -> qw.like("name", searchText)
                            .or()
                            .like("introduction", searchText)
            );
        }
        queryWrapper.eq(ObjUtil.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjUtil.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq(ObjUtil.isNotEmpty(spaceId), "spaceId", spaceId);
        queryWrapper.isNull(nullSpaceId, "spaceId");
        queryWrapper.like(StrUtil.isNotBlank(name), "name", name);
        queryWrapper.like(StrUtil.isNotBlank(introduction), "introduction", introduction);
        queryWrapper.like(StrUtil.isNotBlank(picFormat), "picFormat", picFormat);
        queryWrapper.like(StrUtil.isNotBlank(reviewMessage), "reviewMessage", reviewMessage);
        queryWrapper.eq(StrUtil.isNotBlank(category), "category", category);
        queryWrapper.eq(ObjUtil.isNotEmpty(picWidth), "picWidth", picWidth);
        queryWrapper.eq(ObjUtil.isNotEmpty(picHeight), "picHeight", picHeight);
        queryWrapper.eq(ObjUtil.isNotEmpty(picSize), "picSize", picSize);
        queryWrapper.eq(ObjUtil.isNotEmpty(picScale), "picScale", picScale);
        queryWrapper.eq(ObjUtil.isNotEmpty(reviewStatus), "reviewStatus", reviewStatus);
        queryWrapper.eq(ObjUtil.isNotEmpty(reviewerId), "reviewerId", reviewerId);
        queryWrapper.ge(ObjUtil.isNotEmpty(startEditTime), "editTime", startEditTime);
        queryWrapper.lt(ObjUtil.isNotEmpty(endEditTime), "editTime", endEditTime);
        // JSON 数组查询，把tag的每个标签都拼接起来
        // 每个标签要精确匹配，所以要在前后加上\"表示转义字符的"
        if (CollUtil.isNotEmpty(tags)) {
            // and(tag like "%\"java\"%" and tag like "%\"python\"%")
            for (String tag : tags) {
                queryWrapper.like("tags", "\"" + tag + "\"");
            }
        }
        // 排序
        queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), sortOrder.equals("ascend"), sortField);
        return queryWrapper;
    }

    /**
     * VO转换
     */
    @Override
    public PictureVO getPictureVO(Picture picture, HttpServletRequest request) {
        // 对象转封装类
        PictureVO pictureVO = PictureVO.objToVo(picture);
        // 关联查询用户信息
        Long userId = picture.getUserId();
        if (userId != null && userId > 0) {
            User user = userService.getById(userId);
            UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);
            pictureVO.setUser(userVO);
        }
        return pictureVO;
    }

    /**
     * 分页获取多条图片封装
     */
    @Override
    public Page<PictureVO> getPictureVOPage(Page<Picture> picturePage, HttpServletRequest request) {
        List<Picture> pictureList = picturePage.getRecords();
        // 借助当前页码、每页记录数和总记录数创建
        Page<PictureVO> pictureVOPage = new Page<>(picturePage.getCurrent(), picturePage.getSize(), picturePage.getTotal());
        if (CollUtil.isEmpty(pictureList)) {
            return pictureVOPage;
        }
        // 对象列表 => 封装对象列表
        List<PictureVO> pictureVOList = pictureList.stream().map(PictureVO::objToVo).collect(Collectors.toList());
        // 1. 关联查询用户信息，in(xx,xx,xx)一次查询多条记录，极大提高性能
        Set<Long> userIdSet = pictureList.stream().map(Picture::getUserId).collect(Collectors.toSet());
        // map建立id与用户之间的映射
        // Collectors.groupingBy按照用户id进行分组，实际上只会有一个，但这里自动返回的是列表，所以map的value用了list
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));
        // 2. 填充信息
        pictureVOList.forEach(pictureVO -> {
            Long userId = pictureVO.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            pictureVO.setUser(BeanUtil.copyProperties(user, UserVO.class));
        });
        pictureVOPage.setRecords(pictureVOList);
        return pictureVOPage;
    }

    /**
     * 校验图片
     */
    @Override
    public void validPicture(Picture picture) {
        ThrowUtils.throwIf(picture == null, ErrorCode.PARAMS_ERROR);
        // 从对象中取值
        Long id = picture.getId();
        String url = picture.getUrl();
        String introduction = picture.getIntroduction();
        // 修改数据时，id 不能为空，有参数则校验
        ThrowUtils.throwIf(ObjUtil.isNull(id), ErrorCode.PARAMS_ERROR, "id 不能为空");
        if (StrUtil.isNotBlank(url)) {
            ThrowUtils.throwIf(url.length() > 1024, ErrorCode.PARAMS_ERROR, "url 过长");
        }
        if (StrUtil.isNotBlank(introduction)) {
            ThrowUtils.throwIf(introduction.length() > 800, ErrorCode.PARAMS_ERROR, "简介过长");
        }
    }

    /**
     * 图片审核
     */
    @Override
    public void doPictureReview(PictureReviewRequest pictureReviewRequest, User loginUser) {
        // 1.校验参数
        ThrowUtils.throwIf(pictureReviewRequest == null, ErrorCode.PARAMS_ERROR);
        Long id = pictureReviewRequest.getId();
        Integer reviewStatus = pictureReviewRequest.getReviewStatus();
        PictureReviewStatusEnum enumByValue = PictureReviewStatusEnum.getEnumByValue(reviewStatus);
        String reviewMessage = pictureReviewRequest.getReviewMessage();
        // 参数不能为空或不能从通过或拒绝状态改为待审核状态
        if (id == null || enumByValue == null || PictureReviewStatusEnum.REVIEWING.equals(enumByValue)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 2.判断图片是否存在
        Picture oldPicture = getById(id);
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);
        // 3.校验审核状态修改前后是否相同
        if (oldPicture.getReviewStatus().equals(reviewStatus)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请勿重复审核");
        }
        // 4.数据库操作
        // 只更新需要修改的字段而不是全部update，效率更高
        Picture picture = BeanUtil.copyProperties(pictureReviewRequest, Picture.class);
        picture.setReviewerId(loginUser.getId());
        picture.setReviewTime(new Date());
        boolean result = updateById(picture);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
    }

    /**
     * 填充审核信息
     */
    @Override
    public void fillReviewParams(Picture picture, User loginUser) {
        if (userService.isAdmin(loginUser)) {
            // 管理员自动过审
            picture.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());
            picture.setReviewMessage("管理员自动过审");
            picture.setReviewerId(loginUser.getId());
            picture.setReviewTime(new Date());
        } else {
            // 非管理员，默认待审核
            picture.setReviewStatus(PictureReviewStatusEnum.REVIEWING.getValue());
        }
    }

    /**
     * 批量抓取并上传图片
     *
     * 有两种抓取方式，一种是直接抓网站的html然后解析，另一种是调用网站的后端接口。
     * 这里选择第二种抓微软的图库，虽然返回的也是html但更干净一些，配合jsoup更好解析。
     * 如果抓取的内容次数较多，可以适当地 Thread.sleep 阻塞等待一段时间，减少服务器被封禁的概率
     * （我们这里一次就把所有图片都抓来了而不是一张一张抓，所以不用睡眠）
     */
    @Override
    public Integer uploadPictureByBatch(PictureUploadByBatchRequest pictureUploadByBatchRequest, User loginUser) {
        // 1.校验参数
        String searchText = pictureUploadByBatchRequest.getSearchText();
        Integer count = pictureUploadByBatchRequest.getCount();
        ThrowUtils.throwIf(count == null || count <= 0, ErrorCode.PARAMS_ERROR, "批量上传数量不能为空或小于等于0");
        ThrowUtils.throwIf(count > 30, ErrorCode.PARAMS_ERROR, "最多30条");
        // 2.抓取内容
        // 字符串拼接，抓取网址是微软bing图库，q后面占位符填搜索词
        String fetchUrl = String.format("https://cn.bing.com/images/async?q=%s&mmasync=1", searchText);
        // 调用jsoup抓取并获取html文档
        Document document;
        try {
            document = Jsoup.connect(fetchUrl).get();
        } catch (IOException e) {
            log.error("获取页面失败", e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "获取页面失败");
        }
        // 3.解析内容
        Element div = document.getElementsByClass("dgControl").first();
        if(ObjUtil.isEmpty(div))
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "获取元素失败");
        // 调用img.mimg可选择出所有图片返回一个数组元素
        Elements imgElementList = div.select("img.mimg");
        // 遍历元素，依次处理上传图片
        int uploadCount = 0;
        String namePrefix = pictureUploadByBatchRequest.getNamePrefix(); // 图片名称前缀
        if(StrUtil.isBlank(namePrefix)){
            namePrefix = searchText;
        }
        for (Element imgElement : imgElementList) {
            String src = imgElement.attr("src");// 获取图片地址
            if(StrUtil.isBlank(src)){
                log.info("第{}张图片地址为空，已跳过", uploadCount + 1);
                continue;
            }
            // 处理图片的地址，防止出现转义或与对象存储冲突的问题（地址里问号后面的参数都不要了）
            int questionMarkIndex = src.indexOf("?");
            if(questionMarkIndex > -1)
                src = src.substring(0, questionMarkIndex);
            // 4.上传图片
            PictureUploadRequest pictureUploadRequest = new PictureUploadRequest();
            pictureUploadRequest.setFileUrl(src);
            pictureUploadRequest.setPicName(namePrefix + (uploadCount + 1));
            try {
                uploadPicture(src, pictureUploadRequest, loginUser);
                uploadCount++;
            } catch (Exception e) {
                log.error("第{}张图片上传失败，地址：{}", uploadCount + 1, src, e);
                continue;
            }
            if(uploadCount >= count)
                break;
        }
        return uploadCount;
    }

    /**
     * 清除对象存储中的图片
     *
     * @Async 与在启动类加@EnableAsync可以异步调用方法。默认SimpleAsyncTaskExecutor线程池，线程池大小为10，队列大小为无界
     * 实际开发最好不要用默认线程池，因为所有业务都用默认线程池，可能某个任务把所有池子都占满了别人就没法用了，所以最好还是自定义线程池
     * @param oldPicture
     */
    @Async
    @Override
    public void clearPictureFile(Picture oldPicture) {
        // 判断该图片地址是否只有一条引用，如果有多个地方都引用了就不能删
        String url = oldPicture.getUrl();
        Long count = lambdaQuery().eq(Picture::getUrl, url).count();
        if(count > 1)
            return;
        //对象存储内的地址不包含域名，而数据库内是包含的，所以要先移除域名
        url = url.replaceFirst("https?://[^/]+", "");
        // 删除图片
        cosManager.deleteObject(url);
        // 删除缩略图
        String thumbnailUrl = oldPicture.getThumbnailUrl();
        if(StrUtil.isNotBlank(thumbnailUrl)){
            thumbnailUrl = thumbnailUrl.replaceFirst("https?://[^/]+", "");
            cosManager.deleteObject(thumbnailUrl);
        }

        // 这里做了删除操作写操作，就要考虑数据一致性的问题了
        // 我们只在首页分页查询的时候加入了多级缓存，别的地方没用缓存（其实首页也是走的普通分页查询接口）
        // 但是在swagger接口文档做测试了可以用。
        // 要在一定的性能和一致性之间做取舍。在可以容忍一定的不一致的场景下可以不做过多操作影响性能。
        // 比如我们的首页展示缓存，每过五分钟自己就过期了。我们这个项目只有这一个地方用到了缓存，可以直接拿出来看看有没有设计删除的缓存，
        // 一定要考虑一致性的话也可以直接删掉缓存。

    }

    // 校验空间图片的权限
    @Override
    public void checkPictureAuth(Picture picture, User loginUser) {
        Long spaceId = picture.getSpaceId();
        if (spaceId == null) {
            // 公共图库，仅本人或管理员可操作
            if (!picture.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }
        } else {
            // 私有空间，仅空间管理员可操作
            if (!picture.getUserId().equals(loginUser.getId())) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }
        }
    }

    // 删除图片
    @Override
    public void deletePicture(long pictureId, User loginUser) {
        ThrowUtils.throwIf(pictureId <= 0, ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NO_AUTH_ERROR);
        // 判断是否存在
        Picture oldPicture = this.getById(pictureId);
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);
        // 校验权限 已经改为使用注解鉴权
//        checkPictureAuth(oldPicture, loginUser);
        // 开启事务
        transactionTemplate.execute(status -> {
            // 操作数据库
            boolean result = this.removeById(pictureId);
            ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
            // 释放额度
            Long spaceId = oldPicture.getSpaceId();
            if (spaceId != null) {
                boolean update = spaceService.lambdaUpdate()
                        .eq(Space::getId, spaceId)
                        .setSql("totalSize = totalSize - " + oldPicture.getPicSize())
                        .setSql("totalCount = totalCount - 1")
                        .update();
                ThrowUtils.throwIf(!update, ErrorCode.OPERATION_ERROR, "额度更新失败");
            }
            return true;
        });
        // 清理对象存储中的图片
        this.clearPictureFile(oldPicture);
    }

    // 编辑图片
    @Override
    public void editPicture(PictureEditRequest pictureEditRequest, User loginUser) {
        // 在此处将实体类和 DTO 进行转换
        Picture picture = new Picture();
        BeanUtils.copyProperties(pictureEditRequest, picture);
        // 注意将 list 转为 string
        picture.setTags(JSONUtil.toJsonStr(pictureEditRequest.getTags()));
        // 设置编辑时间
        picture.setEditTime(new Date());
        // 数据校验
        this.validPicture(picture);
        // 判断是否存在
        long id = pictureEditRequest.getId();
        Picture oldPicture = this.getById(id);
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);
        // 校验权限  已经改为使用注解鉴权
//        checkPictureAuth(oldPicture, loginUser);
        // 补充审核参数
        this.fillReviewParams(picture, loginUser);
        // 操作数据库
        boolean result = this.updateById(picture);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
    }

    /**
     * 图片颜色相似度查询
     */
    @Override
    public List<PictureVO> searchPictureByColor(Long spaceId, String picColor, User loginUser) {
        // 1.校验参数
        ThrowUtils.throwIf(spaceId == null || StrUtil.isBlank(picColor), ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NO_AUTH_ERROR);
        // 2.校验空间权限
        Space space = spaceService.getById(spaceId);
        ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
        if (!space.getUserId().equals(loginUser.getId())) // Long等包装类切记都要使用equals()，不能使用!=/==，前者判断值，后者判断地址
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "没有空间访问权限");
        // 3.查询该空间下的所有图片（必须要有主色调）
        List<Picture> list = lambdaQuery()
                .eq(Picture::getSpaceId, spaceId)
                .isNotNull(Picture::getPicColor)
                .list();
        // 如果没有图片，直接返回空列表
        if (list.isEmpty())
            return Collections.emptyList();
        // 将颜色字符串转换为主色调
        Color color = Color.decode(picColor);
        // 4.计算相似度并排序
        List<Picture> pictureList = list.stream().sorted(Comparator.comparing(picture -> {
            String picturePicColor = picture.getPicColor();
            Color color1 = Color.decode(picturePicColor);
            // 相似度越高值越大排序应该越高，sort默认从小到大排列，所以取负
            return -ColorSimilarUtils.calculateSimilarity(color, color1);
        })).limit(12).collect(Collectors.toList());
        // 5.返回结果
        return pictureList.stream().map(PictureVO::objToVo).collect(Collectors.toList());
    }

    /**
     * 批量编辑图片（编辑图片分类，标签，名称）
     */
    @Override
    public void editPictureByBatch(PictureEditByBatchRequest pictureEditByBatchRequest, User loginUser) {
        // 1.获取和校验参数
        List<Long> pictureIdList = pictureEditByBatchRequest.getPictureIdList();
        Long spaceId = pictureEditByBatchRequest.getSpaceId();
        String category = pictureEditByBatchRequest.getCategory();
        List<String> tags = pictureEditByBatchRequest.getTags();
        ThrowUtils.throwIf(CollUtil.isEmpty(pictureIdList), ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(spaceId == null, ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(StrUtil.isBlank(category), ErrorCode.PARAMS_ERROR);
        // 2.校验空间权限
        Space space = spaceService.getById(spaceId);
        ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
        if (!space.getUserId().equals(loginUser.getId())) // Long等包装类切记都要使用equals()，不能使用!=/==，前者判断值，后者判断地址
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "没有空间访问权限");
        // 3.查询指定图片（一定要注意查数据库的时候只查需要的字段，不要写*，一个表有20个字段你只需要查2个这样就节省了10的网络消耗）
        List<Picture> pictureList = lambdaQuery()
                .select(Picture::getId, Picture::getSpaceId)
                .eq(Picture::getSpaceId, spaceId)
                .in(Picture::getId, pictureIdList)
                .list();
        if(pictureList.isEmpty())
            return;
        // 4.更新分类和标签
        pictureList.forEach(picture -> {
            if(StrUtil.isNotBlank(category))
                picture.setCategory(category);
            if(CollUtil.isNotEmpty(tags))
                picture.setTags(JSONUtil.toJsonStr(tags));
        });
        // 批量重命名
        String nameRule = pictureEditByBatchRequest.getNameRule();
        fillPictureWithNameRule(pictureList, nameRule);
        // 5.操作数据库进行批量更新
        boolean result = updateBatchById(pictureList);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "批量编辑失败");
    }

    /**
     * 创建 AI 扩图任务
     * @param createPictureOutPaintingTaskRequest
     * @param loginUser
     */
    @Override
    public CreateOutPaintingTaskResponse createPictureOutPaintingTask(CreatePictureOutPaintingTaskRequest createPictureOutPaintingTaskRequest, User loginUser) {
        // 获取图片信息
        Long pictureId = createPictureOutPaintingTaskRequest.getPictureId();
        Picture picture = Optional.ofNullable(this.getById(pictureId))
                .orElseThrow(() -> new BusinessException(ErrorCode.NOT_FOUND_ERROR));
        // 权限校验  已经改为使用注解鉴权
//        checkPictureAuth(picture, loginUser);
        // 构造请求参数
        CreateOutPaintingTaskRequest taskRequest = new CreateOutPaintingTaskRequest();
        CreateOutPaintingTaskRequest.Input input = new CreateOutPaintingTaskRequest.Input();
        input.setImageUrl(picture.getUrl());
        taskRequest.setInput(input);
        BeanUtil.copyProperties(createPictureOutPaintingTaskRequest, taskRequest);
        // 创建任务
        return aliYunAiApi.createOutPaintingTask(taskRequest);
    }

    /**
     * 批量重命名
     * nameRule 格式：xxx{序号}   eg: 图片6
     * @param pictureList
     * @param nameRule
     */
    private void fillPictureWithNameRule(List<Picture> pictureList, String nameRule) {
        if(StrUtil.isBlank(nameRule))
            return;
        long count = 1;
        try {
            for (Picture picture : pictureList) {
                // replace()直接匹配字符串，replaceAll()用正则表达式匹配，简单替换用前者就行，性能更高一点
                // String name = nameRule.replace("{序号}", String.valueOf(count++));
                String name = nameRule.replaceAll("\\{序号}", String.valueOf(count++)); // 正则表达式{要加\\转义
                picture.setName(name);
            }
        } catch (Exception e) {
            log.error("名称解析错误", e);  // 设计正则表达式，用try-catch包一层保证健壮性
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "名称解析错误");
        }
    }

    /**
     * 批量编辑图片大并发场景优化（编辑图片分类和标签，名称暂时不考虑）
     *
     * 对于我们的؜项目来说，由于用户要处理的数据量不大，上述代码已经能够满足需求。
     * 但如果要处理大量数据，可以使用线程池 + 分批 + 并发进行优化
     */
    @Transactional(rollbackFor = Exception.class)
    public void batchEditPictureMetadata(PictureEditByBatchRequest request, User loginUser) {
        // 参数校验
        List<Long> pictureIdList = request.getPictureIdList();
        Long spaceId = request.getSpaceId();
        String category = request.getCategory();
        List<String> tags = request.getTags();
        ThrowUtils.throwIf(CollUtil.isEmpty(pictureIdList), ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(spaceId == null, ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(StrUtil.isBlank(category), ErrorCode.PARAMS_ERROR);
        Space space = spaceService.getById(spaceId);
        ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
        if (!space.getUserId().equals(loginUser.getId()))
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "没有空间访问权限");

        // 查询空间下的图片
        List<Picture> pictureList = lambdaQuery()
                .select(Picture::getId, Picture::getSpaceId)
                .eq(Picture::getSpaceId, spaceId)
                .in(Picture::getId, pictureIdList)
                .list();

        if (pictureList.isEmpty())
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "指定的图片不存在或不属于该空间");

        // 分批处理避免长事务
        int batchSize = 100;
        List<CompletableFuture<Void>> futures = new ArrayList<>();
        for (int i = 0; i < pictureList.size(); i += batchSize) {
            // sublist()不创建新列表，只引用原列表元素，性能更高
            List<Picture> batch = pictureList.subList(i, Math.min(i + batchSize, pictureList.size()));

            // 异步处理每批数据
            /**
             * CompletableFuture.runAsync(Runnable task, Executor executor)
             * 异步执行一个无返回值的任务（Runnable），并返回一个 CompletableFuture<Void> 对象用于跟踪任务状态。
             * CompletableFuture.supplyAsync(Supplier<T>, Executor)：异步执行有返回值的任务
             *
             * CompletableFuture：基于Future接口扩展，用于多线程异步编排。用 runAsync 处理无返回值的批量任务，
             * 用 supplyAsync 处理有返回值的任务，用 allOf().join() 等待多任务完成，确保批量操作的完整性。
             */
            CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
                batch.forEach(picture -> {
                    if(StrUtil.isNotBlank(category))
                        picture.setCategory(category);
                    if(CollUtil.isNotEmpty(tags))
                        picture.setTags(JSONUtil.toJsonStr(tags));
                });
                boolean result = this.updateBatchById(batch);
                if (!result)
                    throw new BusinessException(ErrorCode.OPERATION_ERROR, "批量更新图片失败");
            }, customExecutor);

            futures.add(future);
        }

        // 阻塞主线程，等待所有任务完成才结束方法
        // futures.toArray(new CompletableFuture[0]将futures从列表转为数组，因为allOf()只接受数组参数
        CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
    }


}




